package org.linlinjava.litemall.admin.web;

import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.card.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.service.AdminGoodsService;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallCoupon;
import org.linlinjava.litemall.db.domain.LitemallCouponUser;
import org.linlinjava.litemall.db.domain.LitemallGoods;
import org.linlinjava.litemall.db.service.LitemallCouponService;
import org.linlinjava.litemall.db.service.LitemallCouponUserService;
import org.linlinjava.litemall.db.service.LitemallGoodsService;
import org.linlinjava.litemall.db.service.LitemallSystemConfigService;
import org.linlinjava.litemall.db.util.CouponConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.ZoneOffset;
import java.util.*;

@RestController
@RequestMapping("/admin/coupon")
@Validated
public class AdminCouponController {
    private final Log logger = LogFactory.getLog(AdminCouponController.class);

    @Autowired
    private LitemallCouponService couponService;
    @Autowired
    private LitemallCouponUserService couponUserService;
    @Autowired
    private AdminGoodsService adminGoodsService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallSystemConfigService systemConfigService;
    @Autowired
    private LitemallGoodsService litemallGoodsService;

    @Autowired
    private WxMpService wxMpService;

    @RequiresPermissions("admin:coupon:list")
    @RequiresPermissionsDesc(menu = {"推广管理", "优惠券管理"}, button = "查询")
    @GetMapping("/list")
    public Object list(String name, Short getType, Short status,
                       @RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer limit,
                       @Sort @RequestParam(defaultValue = "add_time") String sort,
                       @Order @RequestParam(defaultValue = "desc") String order) {
        List<LitemallCoupon> couponList = couponService.querySelective(name, getType, status, page, limit, sort, order);
        return ResponseUtil.okList(couponList);
    }

    @RequiresPermissions("admin:coupon:listuser")
    @RequiresPermissionsDesc(menu = {"推广管理", "优惠券管理"}, button = "查询用户")
    @GetMapping("/listuser")
    public Object listuser(Integer userId, Integer couponId, Short status,
                           @RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer limit,
                           @Sort @RequestParam(defaultValue = "add_time") String sort,
                           @Order @RequestParam(defaultValue = "desc") String order) {
        List<LitemallCouponUser> couponList = couponUserService.queryList(userId, couponId, status, page,
                limit, sort, order);
        return ResponseUtil.okList(couponList);
    }

    private Object validate(LitemallCoupon coupon) {
        String name = coupon.getName();
        if (StringUtils.isEmpty(name)) {
            return ResponseUtil.badArgument();
        }
        return null;
    }

    @RequiresPermissions("admin:coupon:create")
    @RequiresPermissionsDesc(menu = {"推广管理", "优惠券管理"}, button = "添加")
    @PostMapping("/create")
    public Object create(@RequestBody LitemallCoupon coupon) {
        Object error = validate(coupon);
        if (error != null) {
            return error;
        }

        // 如果是兑换码类型，则这里需要生存一个兑换码
        if (coupon.getGetType().equals(CouponConstant.GET_TYPE_CODE)) {
            String code = couponService.generateCode();
            coupon.setCode(code);
        }

        if (coupon.getWxSync()) {
            WxMpCardCreateResult wxMpCardCreateResult = wxAddCoupon(coupon);
            if (wxMpCardCreateResult == null) {
                return ResponseUtil.fail(400, "同步微信失败");
            }
            String cardId = wxMpCardCreateResult.getCardId();
            coupon.setWxCardId(cardId);
        }

        couponService.add(coupon);
        return ResponseUtil.ok(coupon);
    }

    @RequiresPermissions("admin:coupon:read")
    @RequiresPermissionsDesc(menu = {"推广管理", "优惠券管理"}, button = "详情")
    @GetMapping("/read")
    public Object read(@NotNull Integer id) {
        Map map = new HashMap();
        LitemallCoupon coupon = couponService.findById(id);
        map.put("coupon", coupon);
        if (coupon.getGoodsType() == 2) {
            List<LitemallGoods> goods = goodsService.queryByIds(coupon.getGoodsValue());
            map.put("goods", goods);
        }
        return ResponseUtil.ok(map);
    }

    @RequiresPermissions("admin:coupon:update")
    @RequiresPermissionsDesc(menu = {"推广管理", "优惠券管理"}, button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody LitemallCoupon coupon) {
        Object error = validate(coupon);
        if (error != null) {
            return error;
        }
        if (couponService.updateById(coupon) == 0) {
            return ResponseUtil.updatedDataFailed();
        }
        return ResponseUtil.ok(coupon);
    }

    @RequiresPermissions("admin:coupon:delete")
    @RequiresPermissionsDesc(menu = {"推广管理", "优惠券管理"}, button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallCoupon coupon) {
        if (coupon.getWxSync() && coupon.getWxCardId() != null) {
            WxMpCardDeleteResult wxMpCardDeleteResult = wxDeleteCoupon(coupon);
            if (wxMpCardDeleteResult == null) {
                ResponseUtil.fail(400, "删除微信卡卷失败");
            }
        }
        couponService.deleteById(coupon.getId());
        return ResponseUtil.ok();
    }

    private WxMpCardCreateResult wxAddCoupon(LitemallCoupon coupon) {
        Map<String, String> config = systemConfigService.listMail();
        BaseInfo baseInfo = new BaseInfo();
        baseInfo.setLogoUrl("https://mf.mzwise.com/static/img/logo.73183c2.png");
        baseInfo.setCodeType("CODE_TYPE_TEXT");
        baseInfo.setBrandName(config.get("litemall_mall_name"));
        baseInfo.setTitle(coupon.getName());
        baseInfo.setColor("Color010");
        baseInfo.setNotice(coupon.getTag());
        baseInfo.setDescription(coupon.getDesc());
        baseInfo.setGetLimit(coupon.getLimit().intValue());
        Sku sku = new Sku();
        if (coupon.getTotal() == 0) {
            sku.setQuantity(50000); //不限5万
        } else {
            sku.setQuantity(coupon.getTotal());
        }
        baseInfo.setSku(sku);
        DateInfo dateInfo = new DateInfo();
        if (coupon.getTimeType() == 1) { // 绝对时间
            dateInfo.setType("DATE_TYPE_FIX_TIME_RANGE");
            long beginTime = coupon.getStartTime().toEpochSecond(ZoneOffset.of("+8"));
            long endTime = coupon.getEndTime().toEpochSecond(ZoneOffset.of("+8"));
            dateInfo.setBeginTimestamp(beginTime);
            dateInfo.setEndTimestamp(endTime);
        } else { // 相对时间
            dateInfo.setType("DATE_TYPE_FIX_TERM");
            dateInfo.setFixedTerm(coupon.getDays().intValue());
            dateInfo.setFixedBeginTerm(0);
        }
        baseInfo.setDateInfo(dateInfo);
        // 小程序入口
        baseInfo.setCustomUrlName("跳转小程序");
        baseInfo.setCustomAppBrandUserName("gh_9539322da50d@app");
        baseInfo.setCustomAppBrandPass("/page/index/index");
        // 转增
        baseInfo.setCanGiveFriend(true);
        WxMpCardCreateRequest wxMpCardCreateRequest = new WxMpCardCreateRequest();
        if (coupon.getType() == CouponConstant.TYPE_CASH) {
            CashCardCreateRequest cashCardCreateRequest = new CashCardCreateRequest();//不同卡类型不同New以下包装原始略有不同
            CashCard cashCard = new CashCard();
            cashCard.setLeastCost(coupon.getMin().multiply(new BigDecimal(100)).intValue());
            cashCard.setReduceCost(coupon.getDiscount().multiply(new BigDecimal(100)).intValue());
            cashCard.setBaseInfo(baseInfo);
            cashCardCreateRequest.setCash(cashCard);
            wxMpCardCreateRequest.setCardCreateRequest(cashCardCreateRequest);
        } else if (coupon.getType() == CouponConstant.TYPE_GIFT) {
            GiftCardCreateRequest giftCardCreateRequest = new GiftCardCreateRequest();//不同卡类型不同New以下包装原始略有不同
            GiftCard giftCard = new GiftCard();
            giftCard.setBaseInfo(baseInfo);
            giftCard.setGift("Can exchange for a pizza");
            giftCardCreateRequest.setGift(giftCard);
            wxMpCardCreateRequest.setCardCreateRequest(giftCardCreateRequest);
        }
        WxMpCardCreateResult card;
        try {
            card = wxMpService.getCardService().createCard(wxMpCardCreateRequest);
            System.out.println("微信创建代金券接口返回");
            System.out.println(card);
        } catch (WxErrorException e) {
            //todo 同步微信失败失败提示
            System.out.println(e);
            return null;
        }
        return card;
    }


    private Boolean wxEditCoupon(LitemallCoupon coupon) {

        return true;
    }

    private WxMpCardDeleteResult wxDeleteCoupon(LitemallCoupon coupon) {
        try {
            WxMpCardDeleteResult card = wxMpService.getCardService().deleteCard(coupon.getWxCardId());
            System.out.println("微信删除代金券返回");
            System.out.println(card);
            return card;
        } catch (WxErrorException e) {
            System.out.println(e);
            return null;
        }
    }

}
